import React, { useRef, useState } from "react";
import type { ActionType, ProColumns } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import { Button, Divider, Modal } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import { request } from "@@/plugin-request/request";
import { ExclamationCircleOutlined } from "@ant-design/icons/lib";

const { confirm } = Modal;

async function query(params?: Record<string, unknown>) {
  return request(`${process.env.hostname}/admin/merchant/list`, {
    params,
  });
}

async function save(params: any) {
  return request(`${process.env.hostname}/admin/merchant/save`, {
    method: 'post',
    data: params,
    requestType: 'form'
  });
}

function remove(id: number, actionRef: any) {
  confirm({
    title: '确定删除?',
    icon: <ExclamationCircleOutlined />,
    okText: '确定',
    cancelText: '取消',
    onOk() {
      return request(`${process.env.hostname}/admin/merchant/delete`, {
        method: 'post',
        params: { 'id': id }
      }).then(result => {
        if (result.success) {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      })
    }
  });
}


export default (): React.ReactNode => {
  const [modalVisible, handleModalVisible] = useState(false);
  const [formValues, setFormValues] = useState({});
  const [title, setTitle] = useState('')
  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: 'Id',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '登录名',
      dataIndex: 'username',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setFormValues(record);
              setTitle('修改')
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => remove(record.id, actionRef)}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return <PageContainer>
    <ProTable
      actionRef={actionRef}
      search={false}
      rowKey="id"
      toolBarRender={() => [
        <Button type="primary" onClick={() => {
          handleModalVisible(true)
          setFormValues({});
          setTitle('新建')
        }}>
          新建
        </Button>,
      ]}
      request={(params, sorter) => query({ ...params, sorter })}
      columns={columns}
    />

    <Modal width={480} visible={modalVisible} title={title} onCancel={() => handleModalVisible(false)} footer={null} destroyOnClose>
      <ProTable type="form"
                columns={columns}
                rowKey="id"
                form={{ initialValues: formValues }}
                onSubmit={async (value: any) => {
                  const result = await save({ ...formValues, ...value });
                  if (result?.success) {
                    handleModalVisible(false);
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                  }
                }}
      />
    </Modal>

  </PageContainer>;
};

